using System;
using System.Linq;
using Windows.ApplicationModel.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace App43
{
    public static class Helper
    {
        public static async System.Threading.Tasks.Task<Window> Show(this Type type)
        {
            var window = default(Window);
            var coreView = CoreApplication.CreateNewView();
            var view = default(ApplicationView);
            await coreView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                window = Window.Current;
                var frame = new Frame();
                window.Content = frame;
                frame.Navigate(typeof(OtherWindow), null);
                ApplicationView.GetForCurrentView().Consolidated += Helper_Consolidated;
                view = ApplicationView.GetForCurrentView();
            });
            if (await ApplicationViewSwitcher.TryShowAsStandaloneAsync(view.Id))
            {
                await ApplicationViewSwitcher.SwitchAsync(view.Id);
                return window;
            }
            return default(Window);
        }

        public async static void SpecialClose(this Window window)
        {
            await window.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                window.Close();
            });
        }

        static void Helper_Consolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs args)
        {
            sender.Consolidated -= Helper_Consolidated;
            if (!CoreApplication.GetCurrentView().IsMain)
                Window.Current.Close();
        }
    }
}